let generateParent = []; //路由父级元素

//移除文件的"./"字符、扩展名和分割字符
const importAll = r => r.keys().map(key => key.slice(2).replace('.vue', '').split('/'));

//require.context方法导出views文件夹下的vue子文件
const pages = importAll(require.context('../views', true, /\.vue$/));


//生成路由路径
const generateRoute = path => {
    // 注：如果路由以 index 开头则移除第一个元素
    if (path[0].toLowerCase().startsWith('index') && path.length > 1) {
        path.shift()
    }

    // 注：处理根路由
    if (path.length === 1) {
        const shortcut = path[0].toLowerCase()
        return shortcut.startsWith('index')
            ? ''
            // 注：处理动态路由
            : shortcut.startsWith('_')
                ? shortcut.replace('_', ':')
                : shortcut;
    }


    // 注： 处理其他路由
    const lastElement = path[path.length - 1]

    // 注：移除以 index 开头的最后一个元素
    if (lastElement.toLowerCase().startsWith('index')) {
        path.pop()
        // 注：处理动态路由
    } else if (lastElement.startsWith('_')) {
        path[path.length - 1] = lastElement.replace('_', ':');

    }
    return path.map(p => p.toLowerCase()).join('/')
}

//生成父级
pages.forEach(path => {
    if (path.length === 1) {
        generateParent.push({ name: [path[0]].map(p => p.toLowerCase()).join(''), path })
    }
})


//生成子级路径
const childrenByPath = pages
    // 注：筛选出views下的子文件夹内的文件
    .filter(path => path.length >= 2)
    .map(path => {
        const copy = [...path];
        const key = copy[0].toLowerCase();

        return {
            path,
            route: `/${generateRoute(copy)}`,
            key
        }
    })
    .reduce((acc, cur) => {
        // 注：生成键为对应父路由name
        const key = cur.key
        delete cur.key
        if (acc[key]) {
            acc[key].push(cur)
        } else {
            acc[key] = [cur]
        }

        return acc
    }, {})


export default generateParent.map(async parent => {
    let children = [];
    const { default: component } = await import(`../views/${parent.path.join('/')}`)
    const route = `/${generateRoute([...parent.path])}`;

    if (childrenByPath[parent.name]) {
        const promises = childrenByPath[parent.name].map(async ({ path, route }) => {

            const { default: childComponent } = await import(`../views/${path.join('/')}`);
            const { name: childName } = childComponent
            return {
                path: route,
                name: childName,
                component: childComponent
            }
        })

        children = await Promise.all(promises)
    }

    return {
        path: route,
        name: parent.name,
        component,
        children
    }
})
